package com.gxc.datacenter.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;

import com.gxc.datacore.metadata.domain.Column;
import com.gxc.datacore.metadata.domain.Database;
import com.gxc.datacore.metadata.domain.Table;
import com.gxc.datacore.metadata.service.ColumnService;
import com.gxc.datacore.metadata.service.DatabaseService;
import com.gxc.datacore.metadata.service.TableService;
import com.gxc.datacore.metadata.util.CollectUtil;
import com.gxc.dbcore.util.PageInfo;
import com.gxc.dbcore.util.PageList;
import com.gxc.webcore.util.JsonUtil;
import com.gxc.webcore.util.MapUtil;
import com.gxc.webcore.util.RequestUtil;
import com.gxc.webcore.util.StringUtil;

@Controller("datacenter/tableController")
public class TableController {

	@Autowired
	private DatabaseService databaseService;
	@Autowired
	private TableService tableService;
	@Autowired
	private ColumnService columnService;

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public ModelAndView list(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String database_id = request.getParameter("database_id");
		Database database = databaseService.retrieve(database_id);
		Map model = new HashMap();
		model.put("database", database);
		return new ModelAndView("datacenter/manage/table_list.vm", model);
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public ModelAndView grid(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Map params = RequestUtil.getInMap(request);
		PageInfo pageInfo = PageInfo.getFromRequest(request);
		PageList pageList = tableService.listPage(params, pageInfo);
		Map result = new HashMap();
		result.put("status", "success");
		result.put("data", pageList);
		String resultString = JsonUtil.object2json(result);
		response.getWriter().write(resultString);
		return null;
	}

	/**
	 * 采集数据源中的表
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public ModelAndView collocetByDatabase(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String database_id = request.getParameter("database_id");
		Database database = databaseService.retrieve(database_id);
		List list = CollectUtil.getTables(database);
		List tableList = MapUtil.maplist2beanlist(list, Table.class);
		for (int i = 0; i < tableList.size(); i++) {
			Table table = (Table) tableList.get(i);
			try {
				// 采集的表元数据写入数据库
				Table temp = tableService.retrieveByName(database_id,
						table.getSchema_name(), table.getTable_name());
				if (temp != null) {
					table.setId(temp.getId());
					tableService.update(table);
				} else {
					table.setId("table_" + StringUtil.getUUID());
					table.setDatabase_id(database_id);
					tableService.create(table);
				}
				// 采集该表对应的李列元数据
				this.colloceColumnByTable(database, table);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		Map result = new HashMap();
		result.put("status", "success");
		result.put("data", tableList);
		String resultString = JsonUtil.object2json(result);
		response.getWriter().write(resultString);
		return null;
	}

	/**
	 * 查看详细
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public ModelAndView view(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String id = request.getParameter("id");
		Table table = tableService.retrieve(id);
		Map model = new HashMap();
		model.put("table", table);
		return new ModelAndView("system/manage/table_view.vm", model);
	}

	/**
	 * 单个删除
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public ModelAndView delete(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Map result = new HashMap();
		String id = request.getParameter("id");
		int i = tableService.delete(id);
		result.put("status", "success");
		result.put("data", i);
		String resultString = JsonUtil.object2json(result);
		response.getWriter().write(resultString);
		return null;
	}

	/**
	 * 批量删除
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public ModelAndView deleteBatch(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Map result = new HashMap();
		String id = request.getParameter("id");
		String[] id_array = id.split(",");
		int i = tableService.delete(id_array);
		result.put("status", "success");
		result.put("data", i);
		String resultString = JsonUtil.object2json(result);
		response.getWriter().write(resultString);
		return null;
	}

	/**
	 * 采集数据表的列信息
	 * 
	 * @param database
	 * @param table
	 */
	@SuppressWarnings({ "rawtypes" })
	private void colloceColumnByTable(Database database, Table table) {
		List list = CollectUtil.getColumns(database, table.getSchema_name(),
				table.getTable_name());
		List columnList = MapUtil.maplist2beanlist(list, Column.class);
		for (int i = 0; i < columnList.size(); i++) {
			Column column = (Column) columnList.get(i);
			try {
				Column temp = columnService.retrieveByName(table.getId(),
						column.getColumn_name());
				if (temp != null) {
					column.setId(temp.getId());
					columnService.update(column);
				} else {
					column.setId("column_" + StringUtil.getUUID());
					column.setTable_id(table.getId());
					columnService.create(column);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

}
